package com.lin.sunnyweather.logic.network

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

object SunnyWeatherNetwork {

    private val placeService = ServiceCreator.createLocation<LocationService>()

    private val weatherService = ServiceCreator.createWeather<WeatherService>()

    suspend fun searchPlaces(location: String) = placeService.searchPlace(location).await()

    suspend fun nowWeather(location: String) = weatherService.nowWeather(location).await()

    suspend fun threeDayWeather(location: String) = weatherService.threeDayWeather(location).await()

    suspend fun lifeIndex(location: String) = weatherService.lifeIndex(location).await()

    private suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if (body != null) continuation.resume(body)
                    else continuation.resumeWithException(
                        RuntimeException("response body is null,response context:$response")
                    )
                }

                override fun onFailure(call: Call<T>, t: Throwable) {
                    continuation.resumeWithException(t)
                }
            })
        }
    }
}